(function(){
	var fields =  document.querySelectorAll("[data-upload]");

	Array.prototype.forEach.call(fields, function(item){
		uploadChange(item);
	});

	function uploadChange(item){
		item.addEventListener("change", function(){
			var field = this.dataset["upload"],
				texts =  document.querySelector("[data-upload-text='"+field+"']");

			texts.value = this.value;

		});
	}
	var upload_counter = 0;
	function getUploadHtml(){
		upload_counter++;
		return  '<span class="input-upload">\
					<input class="span3" data-upload-text="field_'+upload_counter+'" type="text">\
					<button class="btn" type="button">Upload</button>\
					<input type="file" name="images[]" data-upload="field_'+upload_counter+'">\
				</span>';
	}

	var buttons =  document.querySelectorAll("[data-add-upload]");

	Array.prototype.forEach.call(buttons, function(item){
		item.addEventListener("click", function(){
			var field = this.dataset["addUpload"],
				upload = document.createElement("div"),
				wrapper =  document.querySelector("[data-upload-wrapper='"+field+"']");
			upload.className = "input-append";
			upload.innerHTML = getUploadHtml();
			uploadChange(upload.querySelector("[type=file]"));
			wrapper.appendChild(upload);
		});
	});
})();

(function(){
    var items = $('[name="id[]"]');
    var add = $("#add");
    var remove = $("#delete");
    var edit = $("#edit");
    var action = $("[name=action]");

    remove.bind("click", function(e){
        if(!this.disabled){
            action[0].value="remove";
        }
    });
    add.bind("click", function(e){
        if(!this.disabled){
            action[0].value="add";
        }
    });
    edit.bind("click", function(e){
        if(!this.disabled){
            action[0].value="edit";
        }
    });

    function buttons(){
        var _len = $('[name="id[]"]:checked').length;
        if(_len > 0){
            remove.attr({disabled: false});
            if(_len === 1){
                edit.attr({disabled: false});
            }else{
                edit.attr({disabled: true});
            }
        }else{
            edit.attr({disabled: true});
            remove.attr({disabled: true});
        }
    }
    buttons();
    items.bind("change", function(){
        buttons();
    });
})();